package com.leetCode.problem;

/**
 * Description:
 * Copyright:   Copyright (c)2019
 * Company:     zefu
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2021-11-07 21:10:07
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2021-11-07     张李鑫                     1.0         1.0 Version
 */
public class Problem42 {
    public static void main(String[] args) {
        int[] arr = new int[]{0,1,0,2,1,0,1,3,2,1,2,1};
        System.out.println(trap(arr));
    }


    /**
     * 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图，计算按此排列的柱子，下雨之后能接多少雨水。
     * @param height
     * @return
     */
    public static int trap(int[] height) {
        int[] leftArr = new int[height.length];
        int leftMax = 0;
        int[] rightArr = new int[height.length];
        int rightMax = 0;
        int left = 0;
        int right = height.length - 1;
        //先加工左右数组
        while (left < height.length) {
            leftMax = Math.max(height[left], leftMax);
            leftArr[left++] = leftMax;
            rightMax = Math.max(height[right], rightMax);
            rightArr[right--] = rightMax;
        }

        int sum = 0;
        //拿到左右的最大值 取最小 然后跟自己对比相减
        for (int i = 0; i < leftArr.length - 1; i++) {
            sum += Math.max(0, Math.min(leftArr[i], rightArr[i])-height[i]);
        }
        return sum;
    }

}